<?php
include_once 'library/Controller/BaseController.php';
class AdministratorController extends BaseController implements IController{
	const DEFAULT_CONTROLLER = "_default";
	/**
	 * Data Array of edit form.
	 * @var array 
	 */
	public $objectData = null;
	/**
	 * Data Array of Search Result.
	 * @var array 
	 */
	public $searchResult = null;
	/**
	 * Edit Form.
	 * @var BaseForm
	 */
	public $form = null;
	/**
	 * Search Grid.
	 * @var BaseGrid
	 */
	public $grid = null;
	
	private $previewname = null;
	
	public $userInfo = null;
	protected function _init(){
		if(Auth::hasSession()){
			$this->userInfo = Auth::getSession();
		}
	}
	
	public function indexAction(){
		//$this->previewname = AdministratorController::DEFAULT_CONTROLLER;
	}
	public function searchAction(){
		$viewTitle = ResourceMessage::getInstance()->getMessage($this->getController() ."_list");
		$this->view()->setViewTitle($viewTitle);
		$this->initSearch();
		$se = $this->serializeSearchEntity();
		$se = $this->beforeSearch($se);
		$this->view()->viewData = $se;
		$this->view()->searchResults = $this->getSearchResults($se);
	}
	public function initSearch(){
		
	}
	public function beforeSearch($se){
		return $se;
	}
	protected function serializeSearchEntity(){
		$searchEntity = array();
		$prefix = $this->getTableName() . "_";
		foreach ($this->getContext()->requests() as $key=>$value) {
			if($prefix == substr($key, 0,strlen($prefix))){
				$col = str_replace($prefix, "", $key);
				$searchEntity[$col] = StringUltil::encodeHTML($value);
			}
		}
		$searchEntity[Constant::ORDERBY] = $this->getContext()->request(Constant::ORDERBY, null);
		$searchEntity[Constant::ORDERAS] = $this->getContext()->request(Constant::ORDERAS, null);
		$searchEntity[Constant::PAGE] = $this->getContext()->request(Constant::PAGE, Constant::PAGE_DEFAULT);
		$searchEntity[Constant::SIZE] = $this->getContext()->request(Constant::SIZE, Constant::SIZE_DEFAULT);
		return $searchEntity;
	}
	protected function getSearchResults($searchEntity){
		$db = DBHelper::getInstance();
		$sqlCount = $this->getCountQuery($searchEntity);
		$countResult = $db->fetchRow($sqlCount);
		if(isset($countResult))
			$searchEntity[Constant::TOTAL] = $countResult[Constant::TOTAL];
		$sql = $this->getSearchQuery($searchEntity);
		$searchEntity[Constant::RESULTS] = $db->fetchAll($sql);
		return $searchEntity;
	}
	protected function getSearchQuery($searchEntity){
		return "select * from " . $this->getTableName();
	}
	protected function getCountQuery($searchEntity){
		return "select count(*) as ".Constant::TOTAL." from " . $this->getTableName();
	}
	public function CreateNewSearchEntity(){
		return array();
	}
	public function createNewObject(){
		$obj = array();
		if(isset($this->userInfo)){
			$obj[BaseEntity::CREATEBY] = $this->userInfo[UserSystem::ID];
			$obj[BaseEntity::CREATENAME] = $this->userInfo[UserSystem::NAME];
			$obj[BaseEntity::LASTUPDATEBY] = $this->userInfo[UserSystem::ID];
			$obj[BaseEntity::LASTUPDATENAME] = $this->userInfo[UserSystem::NAME];
		}
		$obj[BaseEntity::CREATETIME] = date("Y-m-d H:i:s");
		$obj[BaseEntity::LASTUPDATETIME] = date("Y-m-d H:i:s");
		$obj[BaseEntity::ROWVERSION] = 0;
		$obj[BaseEntity::STATUS] = Constant::STATUS_ACTIVE;
		$nextID = $this->_model->getEntity()->getNextID();
		if(isset($nextID)){
			foreach ($nextID as $key=>$val) {
				$obj[$key] = $val;
			}
		}
		return $obj;
	}
	
	public function updateAction(){
		$viewTitle = ResourceMessage::getInstance()->getMessage($this->getController() ."_info");
		$this->view()->setViewTitle($viewTitle);
		$entity = $this->_model->getEntity();
		$id = $entity->pkey;
		if($entity != null){
			if($this->getContext()->isPost()){
				$bt = $this->getContext()->postRequest(Constant::BTNEW);
				if(isset($bt))
					$this->executeCreateNew();
				else
						
					$this->executeUpdate();
			}
			else{
				$this->getUpdate();
			}
		}
	}
	public function beforeNew($obj){
		return $obj;
	}
	public function executeCreateNew(){
		$obj = $this->createNewObject();
		$obj = $this->beforeNew($obj);
		$this->view()->viewData = $obj;
		$this->initData();
	}
	public function initData(){
		
	}
	public function initUpdate($obj){
		return $obj;
	}
	/**
	 * Update when request Is Get
	 */
	public function getUpdate(){
		$id = $this->serializeID();
		$obj = null;
		if(isset($id) && count($id)>0){
			$obj = $this->_model->getByIDT($id);
			if(!isset($obj))
				$obj = $this->createNewObject();
		}
		else{
			$obj = $this->createNewObject();
		}
		$obj = $this->initUpdate($obj);
		$this->view()->viewData = $obj;
		$this->initData();
	}
	/**
	 * Update when request Is Post
	 */
	public function executeUpdate(){
		$data = $this->getEntityData();
		$data = $this->beforeUpdate($data);
		$data = $this->validateData($data);
		$entity = $data['entity'];
		if(!$data['isError']){
			$entity = $this->beforeSave($entity);
			$result = $this->_model->insertOrupdate($entity);
			if($result != null){
				$result = $this->initUpdate($result);
				$this->view()->viewData = $result;
				$this->view()->setInfoMessage(ResourceMessage::getInstance()->getMessage("Msg_003"));
			}
			else{
				$entity = $this->initUpdate($entity);
				$this->view()->viewData = $entity;
				$errors = $this->_model->getErrors(); 
				if(isset($errors) && count($errors)>0){
					foreach ($errors as $msg){
						$this->view()->addError($msg);
					}
				}
				else{
					$this->view()->setErrorMessage(ResourceMessage::getInstance()->getMessage("Msg_002"));
				}
			}
		}
		else{
			if(isset($data['errors'])){
				foreach ($data['errors'] as $error){
					$this->view()->addError($error);
				}
			}
			else{
				$this->view()->setErrorMessage(ResourceMessage::getInstance()->getMessage("Msg_002"));
			}
			$entity = $this->initUpdate($entity);
			$this->view()->viewData = $entity;
		}
		$this->initData();
	}
	public function handleUploadImage($entity){
		if(count($_FILES)> 0){
			
		}
	}
	public function beforeSave($obj){
		return $obj;
	}
	public function beforeUpdate($obj){
		if(isset($this->userInfo))
			$obj[BaseEntity::LASTUPDATEBY] = $this->userInfo[UserSystem::ID];
		$obj[BaseEntity::LASTUPDATETIME] = date("Y-m-d H:i:s");
		$obj[BaseEntity::ROWVERSION] = $obj[BaseEntity::ROWVERSION] + 1;
		return $obj;
	}
	public function isErrorData($data){
		return array('isError'=>false,'entity'=>$data,'errors'=>null);
	}
	/**
	 * get ID value from URL or request.
	 * @return multitype:Ambigous <array, string> |NULL of ID value
	 */
	protected function serializeID(){
		$entity = $this->_model->getEntity();
		if(isset($entity->pkey) && count($entity->pkey)>0){
			$id = array();
			foreach ($entity->pkey as $value) {
				$param = $this->getContext()->request($value,"");
				$id[$value] = $param;
			}
			return $id;
		}
		return null;
	}
	public function listAction(){
		$entity = $this->_model->getEntity();
		if(isset($entity)){
			$this->form = FormFactory::minstance($this->getTableName(), $this->getModule());
			$this->grid = GridFactory::minstance($this->getTableName(), $this->getModule());
			$this->grid->setTableName($this->getTableName());
			$this->grid->setContext($this->getContext());
			$this->grid->setForm($this->form);
			
			$this->view()->grid = $this->grid;
		}
//		Debug::print_r($grid);
	}
	public function editAction(){
		$entity = $this->_model->getEntity();
		if(isset($entity)){
			$this->form = FormFactory::minstance($this->getTableName(), $this->getModule()); 
			if($this->getContext()->isPost()){
				$data = $this->_getEntityData();
				$data = $this->form->validate1($data);
				if(isset($data[BaseForm::VAL_HAS_ERROR]) && $data[BaseForm::VAL_HAS_ERROR] == true){
					$error = isset($data[BaseForm::VAL_ERROR_MESSAGE])?$data[BaseForm::VAL_ERROR_MESSAGE]:BaseForm::VAL_ERROR_DEFAULT;
					$this->view()->setErrorMessage($error);
					unset($data[BaseForm::VAL_HAS_ERROR]);
					unset($data[BaseForm::VAL_ERROR_MESSAGE]);
					$this->objectData = ArrayUltils::trim2DotArray($data);
				}
				else {
					$this->objectData = $this->_model->addOrUpdate($data);
					$this->view()->setInfoMessage(BaseForm::MES_SAVE_SUCCESS);
				}
			}
			else{
				$id = array();
				foreach ($entity->pkey as $value) {
					$val = $this->getContext()->getRequest($value,"");
					if($val != "")
						$id[$value] = $val;
				}
				if(count($id) == count($entity->pkey))			
					$this->objectData = $this->_model->getEntity()->getByIDJoin($id);
			}
			$this->view()->form = $this->form;
			$this->view()->objectData = $this->objectData; 
		}
	}
	public function _preView(){
		if($this->view()->getAction() == "edit"||$this->view()->getAction() == "list")
			$this->view()->setController(AdministratorController::DEFAULT_CONTROLLER);
		else if($this->view()->getAction() == "index" && isset($this->previewname)){
			$this->view()->setController($this->previewname);
		}
	} 
	public function _preRun(){
		
	}
	public function _postRun(){
		
	}
	/**
	 * (non-PHPdoc)
	 * @see library/Controller/BaseController::validateData($entity)
	 */
	public function validateData($data){
		return array('isError'=>false,'entity'=>$data,'errors'=>null);
	}
	public function getEntityData(){
		$entity = null;
		$prefix = $this->getTableName() . "_";
		foreach ($this->getContext()->postRequests() as $key=>$value) {
			if($prefix == substr($key, 0,strlen($prefix))){
				$col = str_replace($prefix, "", $key);
				$entity[$col] = StringUltil::encodeHTML($value);
			}
		}
		return $entity;
	}
	public function _getEntityData(){
		$entity = null;
		$prefix = $this->getTableName() . "_";
		foreach ($this->getContext()->postRequests() as $key=>$value) {
			if($prefix == substr($key, 0,strlen($prefix))){
				$col = ":".str_replace($prefix, "", $key);
				$entity[$col] = $value;
			}
		}
		return $entity;
	}
	public function uploadImage($controlname, $name = null){
		$key = $this->getController() . "_" . $controlname;
		if($_FILES[$key]["error"]==0){
			if(!isset($name))
				$name = $this->getController() + $controlname;
			$exts = explode(".", $_FILES[$key]["name"]);
			if(count($exts) > 1)
				$extension = $exts[(count($exts) - 1)];
			else
				$extension = "file";
			$filename = $name .".".$extension;
			$fullpath = MEDIA_IMAGE_PATH . SLASH . strtolower($this->getController());
			$fullpath .= SLASH . $filename;
			if(file_exists($fullpath)){
				$name = $name . "_1";
				$fullpath = MEDIA_IMAGE_PATH . SLASH . strtolower($this->getController());
				$fullpath .= SLASH . $filename;
			}
			if(move_uploaded_file($_FILES[$key]["tmp_name"], $fullpath)){
				return $filename;
			}
			else {
				$msg = ResourceMessage::getInstance()->getMessage("Msg_004");
				$keymsg = ResourceMessage::getInstance()->getMessage($key);
				$message = StringUltil::format($msg, array($keymsg));
				$this->view()->setWaringMessage($message);
				return "";
			}
		}
		else{
			$msg = ResourceMessage::getInstance()->getMessage("Msg_004");
			$keymsg = ResourceMessage::getInstance()->getMessage($key);
			$message = StringUltil::format($msg, array($keymsg));
			$this->view()->setWaringMessage($message);
			return "";
		}
	}
}